package com.icongyou.enterprise.auth.service.impl;

import com.icongyou.enterprise.auth.entity.dto.LoginDto;
import com.icongyou.enterprise.auth.entity.dto.UserHolder;
import com.icongyou.enterprise.auth.entity.vo.LoginUserVo;
import com.icongyou.enterprise.common.result.Result;
import com.icongyou.enterprise.data_aggregation.entity.UserEntity;
import com.icongyou.enterprise.auth.service.AuthService;
import com.icongyou.enterprise.data_aggregation.service.DataAggregationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Autowired
    private DataAggregationService dataAggregationService;

    @Override
    public Result<LoginUserVo> login(LoginDto loginDto) {
        try {
            UserEntity user = dataAggregationService.getUserByAccount(loginDto.getAccount());

            // 空指针问题：先检查user是否为null，再检查userType
            if (user == null) {
                return Result.error(401, "用户不存在");
            }

            // 检查是否为企业用户
            if (user.getUserType() == null || user.getUserType() != 2) {
                return Result.error(401, "用户不存在或用户类型不正确");
            }

            String tenantId = dataAggregationService.selectTenantIdByName(loginDto.getTenants());
            if (tenantId == null) {
                return Result.error(401, "企业不存在或已被禁用");
            }

            // 安全地检查密码，避免空指针
            if (user.getPassword() == null || !user.getPassword().equals(loginDto.getPassword())) {
                return Result.error(401, "密码错误");
            }

            Integer count = dataAggregationService.validateUserTenant(user.getId(), tenantId);
            if (count == null || count == 0) {
                return Result.error(401, "该用户不属于指定企业");
            }

            dataAggregationService.updateUserLastLoginTime(user.getId(), LocalDateTime.now());
            LoginUserVo vo = convertToVo(user);
            // 设置企业ID（使用tenantId）
            vo.setEnterpriseId(tenantId);
            UserHolder.saveUser(vo);
            return Result.success("登录成功", vo);

        } catch (Exception e) {
            return Result.error(500, "系统异常，请稍后重试");
        }
    }



    private LoginUserVo convertToVo(UserEntity user) {
        LoginUserVo vo = new LoginUserVo();
        BeanUtils.copyProperties(user, vo);
        return vo;
    }
}